package com.ocl.www.controller;

import com.ocl.www.domain.User;
import com.ocl.www.domain.UserFans;
import com.ocl.www.service.ArticleService;
import com.ocl.www.service.UserFansService;
import com.ocl.www.service.UserService;
import com.ocl.www.utils.UserUntil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.ocl.www.basic.BasicController;

import java.sql.Timestamp;
import java.util.*;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController
@RequestMapping("/userFans")
public class UserFansController extends BasicController {

    @Autowired
    private UserFansService userFansService;
    @Autowired
    private EhCacheManager em;

    private Logger log = Logger.getLogger(UserFansController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;


    /**
     * 获取未读的粉丝
     * @param maptemp
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectFansWithIsread", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="获取未读的粉丝", notes="获取未读的粉丝(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> selectFansWithIsread (@RequestBody Map<String,Object> maptemp) {

        UserFans  userFans = new UserFans();
        userFans.setUserId(UserUntil.getUserId(SecurityUtils.getSubject().getPrincipals().asSet()));
        List<UserFans> userFansList = null;
        try {
            userFansList =  userFansService.selectFansWithIsread(userFans);
            maptemp.put("info","s");
            maptemp.put("userFanslist",userFansList);
        } catch (Exception e) {
            maptemp.put("info","e");
            maptemp.put("tip",e.getMessage());

        }
        return maptemp;
    }
    /**
     *
     * @Title: UserController
     * @Description: 设置关注
     * @param: @param user
     * @param: @return
     * @return: User
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/setfollow", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="设置关注", notes="设置关注(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> setfollow (@RequestBody Map<String,Object> maptemp) {

        try {
            log.info("secu : "+ SecurityUtils.getSubject().getPrincipals().asList());
//            maptemp.put("islogin",1);
        }catch (NullPointerException E){
            maptemp.put("info","f");
            maptemp.put("tip","no user login");
//            maptemp.put("islogin",0);
            return  maptemp;
        }

        Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
        Object[] obj = new Object[2];
        int obji = 0;
        Iterator<?> it = s.iterator();
        while(it.hasNext()){
            obj[obji] = it.next();
            log.info(obj.getClass());
            log.info(obj.toString());
            obji++;
        }
        Map<String,String> map = (Map<String, String>) obj[1];

        String userId = map.get("userId").toString();
//      log.info(em.getCache("shiroCache").get("user_id"));
        UserFans userFans = new UserFans();
        userFans.setUserId(Integer.valueOf(maptemp.get("userId").toString()));
        userFans.setFansId(Integer.valueOf(userId));

        if (Integer.valueOf(maptemp.get("userId").toString()).equals(Integer.valueOf(userId))){
            maptemp.put("info","f");
            maptemp.put("tip","不可以关注自己");
            return maptemp;
        }
        int alreadyfollow= 0;
        try {
            List<UserFans> userFanslist = new ArrayList<UserFans>();

            userFanslist = userFansService.selectUserFans(userFans);
            alreadyfollow = userFanslist.size();
            if (alreadyfollow >= 1){
                maptemp.put("info","f");
                maptemp.put("tip","不要重复关注");
                return maptemp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());
        userFans.setCreateTime(nousedate);

        int c = 0;
        try {
            c = userFansService.setfollow(userFans);
            log.info("关注成功！");
            maptemp.put("info","s");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maptemp;
    }

    /**
     *
     * @Title: UserController
     * @Description: 获取关注人
     * @param: @param user
     * @param: @return
     * @return: User
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getFollows", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="获取关注人", notes="获取关注人(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public List<UserFans> getFollows (@RequestBody Map<String,Object> maptemp) {

        String userId = maptemp.get("userId").toString();
//      log.info(em.getCache("shiroCache").get("user_id"));

        UserFans userFans = new UserFans();
        userFans.setFansId(Integer.valueOf(maptemp.get("userId").toString()));

        List<UserFans> fanslist = new ArrayList<UserFans>();
        try {
            fanslist = userFansService.getFollows(userFans);
            //log.info("关注成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fanslist;
    }

    /**
     *
     * @Title: UserController
     * @Description: 获取当前用户的关注
     * @param: @param user
     * @param: @return
     * @return: User
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getFollowsForCurrentUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="获取当前用户的关注", notes="获取当前用户的关注(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> getFollowsForCurrentUser (@RequestBody Map<String,Object> maptemp) {

        String userId = maptemp.get("userId").toString();

        UserFans userFans = new UserFans();
        userFans.setFansId(UserUntil.getUserId(SecurityUtils.getSubject().getPrincipals().asSet()));

        List<User> fanslist = new ArrayList<User>();
        try {
            //fanslist = userFansService.getFollows(userFans);
            fanslist = userService.getFollows(userFans);

            maptemp.put("follows",fanslist);

        } catch (Exception e) {
            e.printStackTrace();
        }

//        userFans.setUserId(Integer.valueOf(maptemp.get("userId").toString()));
//        List<User> followslist = new ArrayList<User>();
//        try {
//
//            followslist = userService.getFans(userFans);
//
//            //log.info("fans");
//
//            maptemp.put("fans",followslist);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        return maptemp;
    }


    /**
     *
     * @Title: UserController
     * @Description: 获取关注数，粉丝数
     * @param: @param user
     * @param: @return
     * @return: User
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getFollowsAndFans", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="获取关注人，粉丝人", notes="获取关注人，粉丝人(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> getFollowsAndFans (@RequestBody Map<String,Object> maptemp) {

        String userId = maptemp.get("userId").toString();

        UserFans userFans = new UserFans();
        userFans.setFansId(Integer.valueOf(maptemp.get("userId").toString()));

        List<User> fanslist = new ArrayList<User>();
        try {
            //fanslist = userFansService.getFollows(userFans);
            fanslist = userService.getFollows(userFans);

            maptemp.put("follows",fanslist);

        } catch (Exception e) {
            e.printStackTrace();
        }

        userFans.setUserId(Integer.valueOf(maptemp.get("userId").toString()));
        List<User> followslist = new ArrayList<User>();
        try {

            followslist = userService.getFans(userFans);

            //log.info("fans");

            maptemp.put("fans",followslist);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return maptemp;
    }

    /**
     * 设置粉丝信息为已读isread=1
     * @param maptemp
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserFansOfIsread", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="设置粉丝信息为已读isread=1", notes="设置粉丝信息为已读isread=1(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> updateUserFansOfIsread (@RequestBody Map<String,Object> maptemp) {

        UserFans userFans =new UserFans();
        userFans.setId(Integer.valueOf(maptemp.get("id").toString()));
        int count = 0;
        try {
            count = userFansService.updateUserFansOfIsread(userFans);
            maptemp.put("info","s");
            maptemp.put("tip",count);
        } catch (Exception e) {
//            e.printStackTrace();
            maptemp.put("info","e");
            maptemp.put("tip",e.getMessage());
        }
        return maptemp;
    }
}
